import { Toast } from 'antd-mobile';
import axios from 'axios';
import { getAuth, setAuth } from './storage';
import history from './history';

// 请求基地址
export const baseURL = 'http://geek.itheima.net';

const request = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const { token } = getAuth();
    if (token) {
      (config.headers as any).Authorization = 'Bearer ' + token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    console.dir(error);

    if (!error.response) {
      Toast.show({ content: '网路有问题，请检查网络' });
      return Promise.reject(error);
    }

    if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message });
      return Promise.reject(error);
    }

    const { refresh_token } = getAuth();
    if (!refresh_token) {
      Toast.show({ content: '登录超时，请重新登录' });
      history.push('/login');
      return Promise.reject(error);
    }

    try {
      const res = await axios({
        url: baseURL + '/v1_0/authorizations',
        method: 'PUT',
        headers: {
          Authorization: `Bearer ${refresh_token}`,
        },
      });
      const { token } = res.data.data;
      setAuth({ token, refresh_token });
      return request(error.config);
    } catch (error) {
      Toast.show({ content: '登录超时，请重新登录' });
      history.push('/login');
      return Promise.reject(error);
    }
  }
);

export default request;
